package com.sxt.service.impl;

import com.sxt.entity.Order;
import com.sxt.entity.OrderItem;
import com.sxt.entity.OrderSettlement;
import com.sxt.mapper.OrderItemMapper;
import com.sxt.mapper.OrderMapper;
import com.sxt.mapper.OrderSettlementMapper;
import com.sxt.model.ShopCartItem;
import com.sxt.service.OrderSettlementService;

import lombok.extern.slf4j.Slf4j;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liangtiandong
 * @since 2019-12-17
 */
@Service
@Slf4j
public class OrderSettlementServiceImpl extends ServiceImpl<OrderSettlementMapper, OrderSettlement> implements OrderSettlementService {

	@Autowired
	private OrderSettlementMapper orderSettlementMapper ;
	
	@Autowired
	private OrderMapper orderMapper ;
	
	@Autowired
	private JmsTemplate jmsTemplate ;

	@Autowired
	private OrderItemMapper orderItemMapper ;
	
	/**
	 * 查询订单的结算表
	 */
	@Override
	public OrderSettlement queryOrderByOrderSn(String orderSn) {
		log.info("查询订单编号为{}的结算表",orderSn);
		return orderSettlementMapper.selectOne(new LambdaQueryWrapper<OrderSettlement>().
				    eq(OrderSettlement::getOrderNumber, orderSn));
	}

	@Transactional
	public void updateOrderStatus(String orderSn) {
		log.info("查询订单编号为{}的结算表",orderSn);
		OrderSettlement orderSettlet = orderSettlementMapper.selectOne(new LambdaQueryWrapper<OrderSettlement>().
				    eq(OrderSettlement::getOrderNumber, orderSn));
		orderSettlet.setIsClearing(1);
		orderSettlet.setPayStatus(1);
		orderSettlementMapper.updateById(orderSettlet) ;
		Order order = orderMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNumber, orderSn)) ;
		order.setIsPayed(true);
		order.setPayTime(LocalDateTime.now()) ;
		orderMapper.updateById(order) ;
		 // 若用户支付成功，我们把销量增加
		// prodId prodNum
		List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().
				  select(OrderItem::getProdId,OrderItem::getProdCount).
				  eq(OrderItem::getOrderNumber, orderSn));
		List<ShopCartItem> cartItems = new ArrayList<>(orderItems.size());
		for (OrderItem orderItem : orderItems) {
			ShopCartItem e = new ShopCartItem();
			e.setProdId(orderItem.getProdId());
			e.setProdCount(orderItem.getProdCount());
			cartItems.add(e );
		}
		// 3 搜索引擎的销量 //search-api（使用mq 交互）
		jmsTemplate.convertAndSend("order.decr.stock", cartItems);
		
	}

}
